/*
 * Copyright 2016 Zhongan.com All right reserved. This software is the
 * confidential and proprietary information of Zhongan.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Zhongan.com.
 */
package edu.study.common.util.eventbus;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 类EventbusPublisher.java的实现描述：发布异步消息
 * 
 * @author zhangjinbao 2016年1月25日 下午3:32:09
 */
@Component
public class EventbusPublisher {

    private ThreadPoolExecutor executor;
    private EventBus           asyncBus;

    /**
     * 初始化
     */
    @PostConstruct
    public void init() {
        executor = new ThreadPoolExecutor(30, 30, 0l, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(10000),
                new ThreadFactory() {
                    private AtomicInteger index = new AtomicInteger(0);

                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "za-bio-eventbus-" + index.incrementAndGet());
                    }
                });
        executor.prestartAllCoreThreads();
        asyncBus = new AsyncEventBus(executor);
        asyncBus.register(new EventListener());
    }

    /**
     * @param bean 被回调的对象
     * @param methodName 被回调方法
     * @param args 参数
     * @param clazzs 参数类型
     */
    public void post(Object bean, String methodName, Object[] args, Class<?>[] clazzs) {
        Event event = new Event(bean, methodName, args, clazzs);
        asyncBus.post(event);
    }

    /**
     * @param event
     */
    public void post(Event event) {
        if (null != event) {
            asyncBus.post(event);
        }
    }

}
